import numpy as np

import sys
import os

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "scripts")))
import run_mot_challenge_func

dance_track_path = "/home/konghaomin/Datasets/MaritimeTrackAllData/Spilt/730/DanceTrack"


def eval_tracker(tracker_path):

    res_eval = run_mot_challenge_func.main(
        SPLIT_TO_EVAL="val",
        METRICS=["HOTA", "CLEAR", "Identity"],
        GT_FOLDER=dance_track_path + "/val",
        SEQMAP_FILE=dance_track_path + "/val_seqmap.txt",
        SKIP_SPLIT_FOL=True,
        TRACKERS_TO_EVAL=[""],
        TRACKER_SUB_FOLDER="",
        USE_PARALLEL=True,
        NUM_PARALLEL_CORES=16,
        PLOT_CURVES=False,
        TRACKERS_FOLDER=tracker_path,
    )

    # HOTA
    hota = float(
        np.mean(
            res_eval[0]["MotChallenge2DBox"][""]["COMBINED_SEQ"]["pedestrian"]["HOTA"][
                "HOTA"
            ]
        )
    )

    # DetA AssA MOTA

    deta = float(
        np.mean(
            res_eval[0]["MotChallenge2DBox"][""]["COMBINED_SEQ"]["pedestrian"]["HOTA"][
                "DetA"
            ]
        )
    )

    assa = float(
        np.mean(
            res_eval[0]["MotChallenge2DBox"][""]["COMBINED_SEQ"]["pedestrian"]["HOTA"][
                "AssA"
            ]
        )
    )

    mota = res_eval[0]["MotChallenge2DBox"][""]["COMBINED_SEQ"]["pedestrian"]["CLEAR"][
        "MOTA"
    ]

    idf1 = res_eval[0]["MotChallenge2DBox"][""]["COMBINED_SEQ"]["pedestrian"][
        "Identity"
    ]["IDF1"]

    def convert_result_to_str(result):
        return str(round(result * 100, 3))

    hota, deta, assa, mota, idf1 = (
        convert_result_to_str(hota),
        convert_result_to_str(deta),
        convert_result_to_str(assa),
        convert_result_to_str(mota),
        convert_result_to_str(idf1),
    )

    print("\n" * 3)
    print(f"HOTA DetA AssA MOTA IDF1")
    print(f"{hota} {deta} {assa} {mota} {idf1}")

    # print(convert_result_to_str(result))


def main():
    if len(sys.argv) < 2:
        print("Usage: python Eval_DanceTrack.py <pdf_file_path>")
        sys.exit(1)
        # base_path = "/home/konghaomin/Datasets/MaritimeTrack_Full_Same/DanceTrack/E2E_Result/MOTRv2_Epoch5"
    else:
        base_path = sys.argv[1]

    txt_dir = []
    for root, dirs, files in os.walk(base_path):
        for file in files:
            if file.endswith(".txt") and file != "gt.txt" and "summary" not in file:
                if root not in txt_dir:
                    txt_dir.append(root)

    if len(txt_dir) == 0:
        print("No txt file found in the directory")
        sys.exit(1)

    print(txt_dir)

    for txt in txt_dir:
        eval_tracker(txt)


if __name__ == "__main__":
    main()
